﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.Data;
using CPPEI.Coolzon.Service.Contract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.Server.ServiceImplement
{
    /// <summary>
    /// 切换方案
    /// </summary>
    public class ReqSwitchSolutionHandler : BaseHandler<ReqSwitchSolutionData, RespSwitchSolutionData>
    {
        public ReqSwitchSolutionHandler()
            : base(RESPONSE_SCENARIO.SOLUTION, RESPONSE_COMMAND.SOLUTION.SWITCH)
        {
        }

        protected override RespSwitchSolutionData OnHandle(Data.MainServiceData.Request request, ReqSwitchSolutionData requestData)
        {
            CacheData.ControlDomain domain = CacheData.ServerData.Instance.GetDomain(request.Header.DomainId);
            if (domain != null)
            {
                Common.Logger.InfoToTag("Handler", "client:{0}请求切换方案,domain:{1}从方案:{2}切换到方案:{3}",
                    request.Header.UserIdentity,
                    request.Header.DomainId,
                    domain.SolutionName,
                    requestData.SolutionName);


                #region 清除域里的视图状态
                domain.ResetViewState();
                // 更新视图状态方案信息
                domain.SolutionName = requestData.SolutionName;
                #endregion

                #region 修改终端的状态为正在切换方案
                List<CacheData.Client> clientList = domain.GetClientList();
                for (int index = 0; index < clientList.Count; index++)
                {
                    if (clientList[index].ControlState == CacheData.ControlState.UnderControl)
                    {
                        clientList[index].State = CacheData.ClientState.SwitchSolution;
                    }
                }
                #endregion

                Common.Logger.InfoToTag("Handler", "client:{0}请求切换方案成功,domain:{1}从方案:{2}切换到方案:{3}",
                    request.Header.UserIdentity,
                    request.Header.DomainId,
                    domain.SolutionName,
                    requestData.SolutionName);

                RespSwitchSolutionData responseData = new RespSwitchSolutionData();
                responseData.SolutionName = requestData.SolutionName;
                return responseData;
            }
            else
            {
                Common.Logger.WarningToTag("Handler", "client:{0}请求切换方案:{1}失败,domain:{2}不存在",
                    request.Header.UserIdentity,
                    requestData.SolutionName,
                    request.Header.DomainId);
                return null;
            }
        }
    }
}
